<?php
namespace app\controller;
use think\facade\Log;
use app\model\Token;
use app\model\OpAccount;
class Callback{

    //快手回调地址
    public function kuaishou(){
        $data = input('get.');
        if(!empty($data['state'])){
            Log::write('快手回调信息：开始','info');
            Log::write($data,'info');
            Log::write('快手回调信息：结束','info');
            $rs = $this->get_ks_token($data['auth_code'],$data['state']);
            $rs = $rs->getData();
            
            if($rs['code'] == 0){
                return view('index/no_impower',['name'=>1]);
            }else{
                $url = 'https://ad.e.kuaishou.com/#/openapi/oauth?app_id=165893111&scope=%5B%22report_service%22%2C%22ad_query%22%2C%22ad_manage%22%2C%22account_service%22%5D&redirect_uri=http://oa.mutangtech.com/callback/kuaishou&state='.$data['state'];
            
                return view('index/no_impower',['url'=>$url,'msg'=>$rs['msg']]);
            }
        }else{
            $url = '#';
            
            return view('index/no_impower',['url'=>$url,'msg'=>'获取授权码失败']);
        } 
        
    }
    //快手授权成功，获取token
    public function get_ks_token($auth_code,$state){
        $headers = array( 'Content-Type:application/json');
        $url = 'https://ad.e.kuaishou.com/rest/openapi/oauth2/authorize/access_token';
        $param['app_id'] = C('ks_app_id');
        $param['secret'] = C('ks_secret');
        $param['auth_code'] = $auth_code;
        $rs = http_post($url, $param,'',$headers);
        $rs = json_decode($rs,true);
        if($rs['code'] == 0){
            $data = $rs['data'];
            $data['group'] = 'ksapi';
            $data['advertiser_ids'] = $rs['data']['advertiser_id'];
            $data['expires_in'] = $rs['data']['access_token_expires_in'];
            $data['acc_id'] = $state;
            $w[] = ['group','=','ksapi'];
            $w[] = ['acc_id','=',$state];
            $r = Token::where($w)->find();
            if(empty($r)){
                $s = Token::create($data);
            }else{
                $s = $r->save($data);
            }
        
            if($s){
                OpAccount::where('id',$state)->update(['is_accredit'=>1]);
                return json(['code'=>0,'msg'=>'授权成功']);
            }else{
                return json(['code'=>-1,'msg'=>'授权失败']);
            }
        
        }else{
            return  json(['code'=>$rs['code'],'msg'=>$rs['message']]);
        }
    } 
    
    
    
    
    
    
    
    
    //字节跳动回调地址
    public function zijie(){
        $data = input();
        if(!empty($data['state'])){
            Log::write('字节跳动回调信息：开始','info');
            Log::write($data,'info');
            Log::write('字节跳动回调信息：结束','info');
            $rs = $this->get_token($data['auth_code'],$data['state']);
            $rs = $rs->getData();
            
            if($rs['code'] == 0){
                /* //字节api Token跟新
                $this->get_zjapi_token(); */
                return view('index/no_impower',['name'=>1]);
            }else{
                $url = 'https://ad.oceanengine.com/openapi/audit/oauth.html?app_id=1678787242274819&state='.$data['state'].'&scope=%5B1%2C2%2C3%2C4%2C5%2C8%2C9%5D&material_auth=1&redirect_uri=http%3A%2F%2Foa.mutangtech.com%2Fcallback%2Fzijie&rid=h9r9k7j3xlj';
            
                return view('index/no_impower',['url'=>$url,'msg'=>$rs['msg']]);
            }
        }else{
            $url = '#';
            
            return view('index/no_impower',['url'=>$url,'msg'=>'获取授权码失败']);
        } 
    }
    
    //字节api授权
    function get_token($auth_code='795b4c4a4590bdabb46b630619e5dd1092dbb710',$state){
        if(empty($state)){
            return json(['code'=>-2,'msg'=>'参数异常，授权失败']);
        }
        $headers = array( 'Content-Type:application/json');
        $url = 'https://ad.oceanengine.com/open_api/oauth2/access_token/';
        $param['app_id'] = C('zj_app_id');
        $param['secret'] = C('zj_secret');
        $param['grant_type'] = 'auth_code';
        $param['auth_code'] = $auth_code;
        $rs = http_post($url, $param,'',$headers);
        $rs = json_decode($rs,true);
        
        if($rs['code'] == 0){
            $data = $rs['data'];
            $data['group'] = 'ziapi';
            $data['acc_id'] = $state;
            $data['advertiser_ids'] = implode(',', $rs['data']['advertiser_ids']);
            $wh[] = ['group','=','ziapi'];
            $wh[] = ['acc_id','=',$state];
            $r = Token::where($wh)->find();
            try {
                if(empty($r)){
                    Token::create($data);
                    OpAccount::where('id',$state)->update(['is_accredit'=>1]);
                }else{
                    $r->save($data);
                }
                
                return json(['code'=>0,'msg'=>'授权成功']);
            } catch (\Exception $e) {
                OpAccount::where('id',$state)->update(['is_accredit'=>0]);
                return json(['code'=>-1,'msg'=>'授权失败']);
            }
            
            
        }else{
            return  json(['code'=>$rs['code'],'msg'=>$rs['message']]);
        }
        
    }
    
    
    //跟新tonke
    public function get_save_token(){
        //字节api Token跟新
        $this->get_zjapi_token();
        //快手刷新 token
        $this->ks_save_token();
    }
    //字节api Token跟新
    function get_zjapi_token(){
        $list = Token::where('group','ziapi')->select();
        if(empty($list)){
            echo '没有需要跟新的字节跳动Token';
            Log::write('没有需要跟新的字节跳动Token','info');
            
            exit();
        }
        foreach ($list as $k=>$v){
            $rs = $this->get_save_zj_token($v['refresh_token']);
            $rs = json_decode($rs,true);
            if($rs['code'] == 0){
                $this->get_db($v['id'],$rs);
            }else{
                echo '字节跳动Token跟新失败,失败原因：'.$rs['message'].'<br>';
                Log::write('字节跳动Token跟新失败,失败原因：'.$rs['message'],'info');
            }
            
        }
       
    }
    function get_db($id,$rs){
        $wh[] = ['group','=','ziapi'];
        $wh[] = ['id','=',$id];
        $r = Token::where($wh)->update($rs['data']);
        if($r){
            echo '字节跳动Token跟新成功<br>';
            Log::write('字节跳动Token跟新成功','info');
        }else{
            echo '字节跳动Token跟新失败<br>';
            Log::write('字节跳动Token跟新失败','info');
        }
    }
    function get_save_zj_token($refresh_token){
        $headers = array( 'Content-Type:application/json');
        $url = 'https://ad.oceanengine.com/open_api/oauth2/refresh_token/';
        $param['app_id'] = C('zj_app_id');
        $param['secret'] = C('zj_secret');
        $param['grant_type'] = 'refresh_token';
        $param['refresh_token'] = $refresh_token;
        $rs = http_post($url, $param,'',$headers);
        return $rs;
    }
    
    //快手刷新 token
    public function ks_save_token(){
        $list = Token::where('group','ksapi')->select();
        if(empty($list)){
            echo '没有需要跟新的快手Token';
            Log::write('没有需要跟新的快手Token','info');
            exit();
        }
        foreach ($list as $k=>$v){
            $this->get_ks_save_token($v['refresh_token'],$v['id']);
            
        }

    }
    public function get_ks_save_token($refresh_token,$id){
        $headers = array( 'Content-Type:application/json');
        $url = 'https://ad.e.kuaishou.com/rest/openapi/oauth2/authorize/refresh_token';
        $param['app_id'] = C('ks_app_id');
        $param['secret'] = C('ks_secret');
        $param['refresh_token'] = $refresh_token;
        
        $rs = http_post($url, $param,'',$headers);
        $rs = json_decode($rs,true);
        
        if($rs['code'] == 0){
            $data['access_token'] = $rs['data']['access_token'];
            $data['refresh_token'] = $rs['data']['refresh_token'];
            $data['refresh_token_expires_in'] = $rs['data']['refresh_token_expires_in'];
            $data['advertiser_ids'] = $rs['data']['advertiser_id'];
            $data['expires_in'] = $rs['data']['access_token_expires_in'];
            $data['id'] = $id;
            try {
                Token::update($data);
                echo '快手Token跟新成功';
            } catch (\Exception $th) {
                //throw $th;
                echo '快手Token跟新失败'.$th->getMessage();
                Log::write('快手Token跟新失败'.$th->getMessage(),'info');
            }
        }else{
            echo '快手Token跟新失败,失败原因：'.$rs['message'];
            Log::write('快手Token跟新失败,失败原因：'.$rs['message'],'info');
        }
    }
    
    ///字节跳动，第三方服务
    public function zj_third_party(){
        $data = input();
        Log::write('字节跳动，第三方服务回调信息：开始','info');
        Log::write($data,'info');
        Log::write('字节跳动，第三方服务回调信息：结束','info');
    }
    


    // 腾讯广点通回调地址
    public function tencent(){
        $data = input('get.');
        if(!empty($data['state']) && !empty($data['authorization_code'])){
            Log::write('广点通回调信息：开始','info');
            Log::write($data,'info');
            Log::write('广点通回调信息：结束','info');
            $rs = $this->get_qq_token($data['authorization_code'],$data['state']);
            $rs = $rs->getData();
        
            if($rs['code'] == 0){
                return view('index/no_impower',['name'=>1]);
            }else{
                // https://developers.e.qq.com/oauth/authorize?client_id=1111497956&redirect_uri=http%3A%2F%2Foa.mutangtech.com%2FCallback%2Ftencent&state='+id;
                $url = 'https://developers.e.qq.com/oauth/authorize?client_id=1111497956&redirect_uri=http%3A%2F%2Foa.mutangtech.com%2FCallback%2Ftencent&state='.$data['state'];
            
                return view('index/no_impower',['url'=>$url,'msg'=>$rs['msg']]);
            }
        }else{
            $url = '#';
            
            return view('index/no_impower',['url'=>$url,'msg'=>'获取授权码失败']);
        } 
       
    }
    // 获取广点通token
    function get_qq_token($auth_code,$state){
        if(empty($state) || empty($auth_code)){
            return json(['code'=>-2,'msg'=>'参数异常，授权失败']);
        }
        $headers = array( 'Content-Type:application/json');
        $url = 'https://api.e.qq.com/oauth/token?client_id=1111497956&client_secret=GzXV05aaLEthrb5F&grant_type=authorization_code&authorization_code='.$auth_code.'&redirect_uri=http://oa.mutangtech.com/Callback/tencent';
       
        $rs = http_get($url,$headers);
        $rs = json_decode($rs,true);
        Log::write('广点通回调信息：开始','info');
        Log::write($rs,'info');
        Log::write('广点通回调信息：结束','info');
        if($rs['code'] == 0){
            // $data = $rs['data'];
            $data['group'] = 'qq';
            $data['acc_id'] = $state;
            $data['advertiser_ids'] = $rs['data']['authorizer_info']['account_id'];
            $data['access_token'] = $rs['data']['access_token'];
            $data['expires_in'] = $rs['data']['access_token_expires_in'];
            $data['refresh_token'] = $rs['data']['refresh_token'];
            $data['refresh_token_expires_in'] = $rs['data']['refresh_token_expires_in'];
            $wh[] = ['group','=','qq'];
            $wh[] = ['acc_id','=',$state];
            $r = Token::where($wh)->find();
            try {
                if(empty($r)){
                    Token::create($data);
                    OpAccount::where('id',$state)->update(['is_accredit'=>1]);
                }else{
                    $r->save($data);
                }
                
                return json(['code'=>0,'msg'=>'授权成功']);
            } catch (\Exception $e) {
                OpAccount::where('id',$state)->update(['is_accredit'=>0]);
                return json(['code'=>-1,'msg'=>'授权失败']);
            }
            
            
        }else{
            return  json(['code'=>$rs['code'],'msg'=>$rs['message']]);
        }
    }


    // 知乎回调
    public function zhihu(){
        if(request()->isPost() && input('t')=='json'){
            $acc_id = input('post.acc_id');
            $name_id = input('post.name_id');
            $token = input('post.token');
            $data['group'] = 'zhihu';
            $data['acc_id'] = $acc_id;
            $data['advertiser_ids'] = $name_id;
            $data['access_token'] = $token;
            $wh[] = ['group','=','zhihu'];
            $wh[] = ['acc_id','=',$acc_id];
            $r = Token::where($wh)->find();
            try {
                if(empty($r)){
                    Token::create($data);
                    OpAccount::where('id',$acc_id)->update(['is_accredit'=>1]);
                }else{
                    $r->save($data);
                }
                
                return json(['code'=>1,'msg'=>'授权成功']);
            } catch (\Exception $e) {
                OpAccount::where('id',$acc_id)->update(['is_accredit'=>0]);
                return json(['code'=>0,'msg'=>'授权失败']);
            }
        }
    }
  

















    
}